package cn.itcast.wanxinp2p.account.service.impl;

import cn.itcast.wanxinp2p.account.entity.Account;
import cn.itcast.wanxinp2p.account.mapper.AccountMapper;
import cn.itcast.wanxinp2p.account.service.AccountService;
import cn.itcast.wanxinp2p.account.service.SmsService;
import cn.itcast.wanxinp2p.api.account.model.AccountDTO;
import cn.itcast.wanxinp2p.api.account.model.AccountRegisterDTO;
import cn.itcast.wanxinp2p.common.domain.RestResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {

    @Autowired
    private SmsService smsService;

    @Override
    public RestResponse getSMSCode(String mobile) {
        return smsService.getSmsMessageCode(mobile);
    }

    @Override
    public RestResponse<Integer> checkMobile(String mobile, String key, String code) {

        //检查校验码
        smsService.verifySmsCode(key,code);
        //
        LambdaQueryWrapper<Account> queryWrappers = new LambdaQueryWrapper<>();
        queryWrappers.eq(Account::getMobile,mobile);
        int count = this.count(queryWrappers);
        if (count > 0){
            //用户存在  直接登录
            return RestResponse.success(1);
        }else {
            //用户不存在  注册再登录
            return RestResponse.success(0);
        }
    }

    @Override
    public AccountDTO register(AccountRegisterDTO registerDTO) {

        Account account = new Account();
        //获取用户注册的数据  保存到数据库

        //简化
        /*String mobile = registerDTO.getMobile();
        String username = registerDTO.getUsername();
        String password = registerDTO.getPassword();

        // DTO转成Entity
        account.setMobile(mobile);
        account.setUsername(username);
        account.setPassword(password);*/
        BeanUtils.copyProperties(registerDTO,account);

        this.saveOrUpdate(account);

        //转换成dto返回
        AccountDTO accountDTO = new AccountDTO();
        /*accountDTO.setMobile(mobile);
        accountDTO.setUsername(username);*/
        BeanUtils.copyProperties(account,accountDTO);

        return accountDTO;
    }


}
